package com.example.weight;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.weight.util.ScreenUtils;
import com.joker.annotation.PermissionsDenied;
import com.joker.annotation.PermissionsGranted;
import com.joker.api.Permissions4M;
import com.example.weight.deprecate.CameraActivity;

import java.io.File;

/**
 * 网页
 *
 * @author zcs
 * @date 2017/12/19 0019
 */

public class WebActivity extends AppCompatActivity{

    TextView tvTitle;
    ImageView ivBack;
    WebView webView;
    ImageView rightReturn;

    private String platform;

    public static final int INPUT_FILE_REQUEST_CODE = 1;
    private final static int FILECHOOSER_RESULTCODE = 2;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mFilePathCallback;
    private static final int CAMERA_CODE = 101;
    private static final int READ_CODE = 102;
    private static final int WRITE_CODE = 103;

    private int goRequestCode = 0;
    private boolean isPermissionsOk = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_web);
        initWeb();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
            }
        });
        rightReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initWeb() {
        webView.requestFocusFromTouch();//支持获取手势焦点，便于用户输入
        WebSettings settings = webView.getSettings();
        String dir = getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        //启用地理定位
        settings.setGeolocationEnabled(true);
        //设置定位的数据库路径
        settings.setGeolocationDatabasePath(dir);
        settings.setDomStorageEnabled(true);//是否开启本地DOM存储
        settings.setJavaScriptEnabled(true);//启用支持javascript
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//优先不使用缓存
        settings.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
        settings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        settings.setDisplayZoomControls(false);//不显示缩放控制按钮（3.0以上有效）
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
        webView.setDownloadListener(new CustomDownload());
        webView.setWebViewClient(webViewClient);
        webView.setWebChromeClient(webChromeClient);
    }

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null) {
                if (url.contains("http://www.dqkshare.com/?qslshare=")) {
                    platform = url.substring(url.length() - 1);
                    return true;
                } else if (url.contains("http://www.windowsmonico.com/?status=")) {
                    return true;
                } else if (url.startsWith("mqqwpa://im/chat")) {
                    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(in);
                    return true;
                }
            }
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            Log.e("error", error.toString());
        }
    };
    private WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            tvTitle.setText(title);
        }

        // For Android 3.0-
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
//            showCamera(FILECHOOSER_RESULTCODE);
            goRequestCode = FILECHOOSER_RESULTCODE;
            if(isPermissionsOk) {
                showCamera(goRequestCode);
            }else {
                requestPermissions(CAMERA_CODE);
            }
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
//            showCamera(FILECHOOSER_RESULTCODE);
            goRequestCode = FILECHOOSER_RESULTCODE;
            if(isPermissionsOk) {
                showCamera(goRequestCode);
            }else {
                requestPermissions(CAMERA_CODE);
            }
        }

        // For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
//            showCamera(FILECHOOSER_RESULTCODE);
            goRequestCode = FILECHOOSER_RESULTCODE;
            if(isPermissionsOk) {
                showCamera(goRequestCode);
            }else {
                requestPermissions(CAMERA_CODE);
            }
        }

        // android 5.0
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;
//            showCamera(INPUT_FILE_REQUEST_CODE);
            goRequestCode = INPUT_FILE_REQUEST_CODE;
            if(isPermissionsOk) {
                showCamera(goRequestCode);
            }else {
                requestPermissions(CAMERA_CODE);
            }
            return true;
        }
    };

    @Override
    public void onDestroy() {
        if (webView != null) {
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onResume() {
        webView.onResume();
        super.onResume();
        if(Build.VERSION.SDK_INT >= 21){
            if(mFilePathCallback != null){
                mFilePathCallback.onReceiveValue(null);
                mFilePathCallback = null;
            }
            return;
        }

        if(mUploadMessage != null){
            mUploadMessage.onReceiveValue(null);
            mUploadMessage = null;
        }
    }

    @Override
    public void onPause() {
        webView.onPause();
        super.onPause();
    }

    class CustomDownload implements DownloadListener{

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            if(Uri.parse(url).getPath().endsWith(".apk") || url.endsWith(".apk")){
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        }
    }

    /*** 下面代码是为了处理webview上传文件用, 只供参考 ***/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if(resultCode != RESULT_OK){
            if(mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }

            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
                mFilePathCallback = null;
            }
            return;
        }
        if (requestCode == FILECHOOSER_RESULTCODE) {
            mUploadMessage.onReceiveValue(Uri.fromFile(new File(intent.getStringExtra(CameraActivity.KEY_IMAGE))));
            mUploadMessage = null;
        } else if (requestCode == INPUT_FILE_REQUEST_CODE && mFilePathCallback != null) {
            // 5.0的回调
            mFilePathCallback.onReceiveValue(new Uri[]{Uri.fromFile(new File(intent.getStringExtra(CameraActivity.KEY_IMAGE)))});
            mFilePathCallback = null;
        }
    }

    private void showCamera(int requestCode){
        Intent intent = new Intent(WebActivity.this, CameraActivity.class);
        startActivityForResult(ScreenUtils.getWindow(intent, getWindow().getDecorView()), requestCode);
    }

    private void requestPermissions(int code) {
        if (code == CAMERA_CODE) {
            Permissions4M.get(this)
                    // 是否强制弹出权限申请对话框，建议设置为 true，默认为 true
                    .requestForce(true)
                    // 是否支持 5.0 权限申请，默认为 false
                    // .requestUnderM(false)
                    // 权限，单权限申请仅只能填入一个
                    .requestPermissions(Manifest.permission.CAMERA)
                    // 权限码
                    .requestCodes(CAMERA_CODE)
                    // 如果需要使用 @PermissionNonRationale 注解的话，建议添加如下一行
                    // 返回的 intent 是跳转至**系统设置页面**
                    .requestPageType(Permissions4M.PageType.MANAGER_PAGE)
                    // 返回的 intent 是跳转至**手机管家页面**
                    // .requestPageType(Permissions4M.PageType.ANDROID_SETTING_PAGE)
                    .request();

        } else if (code == READ_CODE) {
            Permissions4M.get(this)
                    // 是否强制弹出权限申请对话框，建议设置为 true，默认为 true
                    .requestForce(true)
                    // 是否支持 5.0 权限申请，默认为 false
                    // .requestUnderM(false)
                    // 权限，单权限申请仅只能填入一个
                    .requestPermissions(Manifest.permission.READ_EXTERNAL_STORAGE)
                    // 权限码
                    .requestCodes(READ_CODE)
                    // 如果需要使用 @PermissionNonRationale 注解的话，建议添加如下一行
                    // 返回的 intent 是跳转至**系统设置页面**
                    .requestPageType(Permissions4M.PageType.MANAGER_PAGE)
                    // 返回的 intent 是跳转至**手机管家页面**
                    // .requestPageType(Permissions4M.PageType.ANDROID_SETTING_PAGE)
                    .request();
        } else if (code == WRITE_CODE) {
            Permissions4M.get(this)
                    // 是否强制弹出权限申请对话框，建议设置为 true，默认为 true
                    .requestForce(true)
                    // 是否支持 5.0 权限申请，默认为 false
                    // .requestUnderM(false)
                    // 权限，单权限申请仅只能填入一个
                    .requestPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    // 权限码
                    .requestCodes(WRITE_CODE)
                    // 如果需要使用 @PermissionNonRationale 注解的话，建议添加如下一行
                    // 返回的 intent 是跳转至**系统设置页面**
                    .requestPageType(Permissions4M.PageType.MANAGER_PAGE)
                    // 返回的 intent 是跳转至**手机管家页面**
                    // .requestPageType(Permissions4M.PageType.ANDROID_SETTING_PAGE)
                    .request();
        }
    }

    @PermissionsGranted({CAMERA_CODE, READ_CODE, WRITE_CODE})
    public void onPermissionsGranted(int code) {
        if (code == CAMERA_CODE) {
            requestPermissions(READ_CODE);
        } else if (code == READ_CODE) {
            requestPermissions(WRITE_CODE);
        } else {
            isPermissionsOk = true;
            if(goRequestCode != 0) {
                showCamera(goRequestCode);
            }
        }
    }

    @PermissionsDenied({CAMERA_CODE, READ_CODE, WRITE_CODE})
    public void onPermissionsDenied(int code) {
        if (code == CAMERA_CODE) {
        } else {
        }
    }
}
